<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Arts\WebArticleModel;
use App\Models\Arts\WebMenusModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

/**
 * 首页
 * Author:panda
 * Email:joeyoung0314@qq.com
 * Class ArticleController
 * @package App\Http\Controllers\Home
 */
class ModuleController extends Controller
{
    public function index(Request $request, $module, $page = '')
    {
        // 当前栏目信息
        $menus = WebMenusModel::query()->where('link', $module);

        if (!empty($page)) {
            $menus->where('id', $page);
        }

        $menus = $menus->where('status', 1)->where('is_delete', 0)->first();
        if (!$menus) abort(404);
        if (empty($menus['module_page'])) abort(404);//如果没有指定模板也，则404
        if ($menus['pinyin'] === 1 && empty($page)) abort(404);//如果是自动链接，一定会有page，如果没有则404
        $view['info'] = $menus;

        //下级文章列表
        if (in_array($menus['module_page'], ['article'])) {
            // 栏目信息
            $left_id = $menus['level'] == 1 ? $menus['id'] : $menus['parent_id'];
            $menusLink = $page ? "/{$module}/{$page}" : "/{$module}";
            $left_menus = WebMenusModel::query()->where('parent_id', $left_id)->where('status', 1)->where('is_delete', 0)->orderBy('sort', 'desc')->get();
            foreach ($left_menus as $key => $val) {
                $tail = $val['pinyin'] == 1 ? '/' . $val['id'] : '';
                $left_menus[$key]['link'] = '/' . $val['link'] . $tail;
                $left_menus[$key]['active'] = $left_menus[$key]['link'] == $menusLink ? 1 : 0;
            }
            $view['left_menus'] = $left_menus;

            $list = WebArticleModel::query()->select(['id', 'menus_id', 'tags', 'title', 'image', 'is_image', 'description', 'created_at'])
                ->where('menus_id', $menus['id'])
                ->where('status', 1)
                ->where('is_delete', 0)
                ->orderBy('sort', 'desc')
                ->orderBy('created_at', 'desc')
                ->paginate(16);
            foreach ($list as $item) {
                $item->menus_link = "/{$module}/{$item['menus']['id']}";
                $item->link = "/{$module}/{$item['id']}.html";
                $item->image = explode(',', $item->image);
                $item->tags = !empty($item->tags) ? explode(',', $item->tags) : '';
            }
            $view['list'] = $list;
        }

        //seo
        $view['seo_title'] = $menus['seo_title'] ?? "";
        $view['seo_keywords'] = $menus['seo_keywords'] ?? '';
        $view['seo_description'] = $menus['seo_description'] ?? '';
        return view("home.module." . $menus['module_page'], $view);
    }

    public function details(Request $request, $id)
    {
        // 客户端IP
        $ip = $_SERVER['HTTP_X_REAL_IP'] ?? Request::capture()->getClientIp();
        //增加访问记录
        WebArticleModel::query()->where('id',$id)->increment('pv');
        Cache::remember("$ip:$id",1800,function () use ($id){
            //增加访问记录
            WebArticleModel::query()->where('id',$id)->increment('uv');
        });

        $info = WebArticleModel::query()
            ->select(['id', 'menus_id', 'tags', 'title', 'image', 'is_image', 'description', 'content', 'created_at', 'pv', 'uv', 'like'])
            ->with(['menus' => function ($query) {
                $query->select('id', 'name');
            }])
            ->where('id', $id)
            ->where('status', 1)
            ->where('is_delete', 0)
            ->first();
        if (!$info) {
            abort(404);
        }

        $info['tags'] = !empty($info['tags']) ? explode(',', $info['tags']) : '';

        //获取上下篇
        $UpNext = $this->getUpNext($id, $info['menus_id']);
        //获取上下篇 end.

        // seo
        $seo_title = $info['seo_title'] ?? '';
        $seo_keywords = $info['seo_keywords'] ?? '';
        $seo_description = $info['seo_description'] ?? '';

        unset($info['seo_title'], $info['seo_keywords'], $info['seo_description']);

        return view("home.module.details", [
            'info' => $info,
            'up' => $UpNext['up'],
            'next' => $UpNext['next'],
            'commentList' => [],
            'seo_title' => $seo_title,
            'seo_keywords' => $seo_keywords,
            'seo_description' => $seo_description
        ]);
    }

    //缓存获取上下篇
    public function getUpNext($id, $type)
    {
        return Cache::remember('article_up_next_' . $id, 86400, function () use ($id, $type) {
            $list = WebArticleModel::query()
                ->select(['id', 'menus_id', 'tags', 'title', 'image', 'is_image', 'description', 'content', 'created_at'])
                ->where('menus_id', $type)
                ->where('status', 1)
                ->where('is_delete', 0)
                ->orderBy('sort', 'desc')
                ->orderBy('created_at', 'desc')
                ->get();
            $up = [];
            $next = [];
            foreach ($list as $key => $val) {
                if ($val->id == $id) {
                    $up = !empty($list[$key - 1]) ? $list[$key - 1] : [];
                    $next = !empty($list[$key + 1]) ? $list[$key + 1] : [];
                }
            }
            return [
                'up' => $up,
                'next' => $next,
            ];
        });
    }
}